package com.adminserver.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.adminserver.customEntity.SaltEntity;
import com.adminserver.entity.AdminEntity;
import com.adminserver.entity.AdminJobRecordEntity;
import com.adminserver.entity.UserRoleEntity;
import com.adminserver.mapper.AdminMapper;
import com.adminserver.service.AdminJobRecordService;
import com.adminserver.service.AdminService;
import com.adminserver.service.UserRoleService;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminService adminService;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    SaltEntity saltEntity;

    @Autowired
    AdminJobRecordService adminJobRecordService;

    @Autowired
    UserRoleService userRoleService;

    /**
     * 系统账号
     */
    @Value("${system-account.account}")
    private String sys_account;

    /**
     * 获取系统账号
     *
     * @return
     */
    public String getSystemAccount() {
        return DigestUtil.md5Hex(DigestUtil.md5Hex(sys_account).concat(saltEntity.getAccount()));
    }

    @GetMapping("/pullAllAdmin")
    public ResponseUtil pullAllAdmin() {
        List<AdminEntity> adminEntities = adminMapper.queryAllAdminAndState();
        adminEntities.forEach(item -> item.setPassword(null));
        return ResponseUtil.setE(ResponseEnum.OK).setData(adminEntities);
    }

    @Transactional
    @PostMapping("/addNewAdmin")
    public ResponseUtil addNewAdmin(@RequestBody AdminEntity adminEntity) {
        if (adminEntity == null) return ResponseUtil.setE(ResponseEnum.PARAMS_ERROR);
        String handleSaltAccount = DigestUtil.md5Hex(adminEntity.getAccount().concat(saltEntity.getAccount()));
        String handleSaltPassword = DigestUtil.md5Hex(adminEntity.getPassword().concat(saltEntity.getPassword()));
        adminEntity.setAccount(handleSaltAccount);
        adminEntity.setPassword(handleSaltPassword);
        adminEntity.setRegisterTime(DateUtil.date());
        try {
            adminService.save(adminEntity);
            UserRoleEntity entity = new UserRoleEntity();
            entity.setUserId(adminEntity.getAccount());
            entity.setRoleId(adminEntity.getRoleId());
            entity.setEnabled(true);
            userRoleService.save(entity);
            // 系统账号---默认在线
            if (adminEntity.getAccount().equals(getSystemAccount())) {
                AdminJobRecordEntity adminJobRecord = new AdminJobRecordEntity();
                adminJobRecord.setAccount(adminEntity.getAccount());
                adminJobRecord.setOnGuard(true);
                adminJobRecord.setStartingDate(DateUtil.date());
                adminJobRecordService.save(adminJobRecord);
            }
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("新增管理员 " + adminEntity.getName() + " 成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("新增管理员失败，请稍候再试");
        }
    }

    @Transactional
    @PostMapping("/delAdmin")
    public ResponseUtil delAdmin(@RequestBody AdminEntity adminEntity) {
        try {
            if (adminEntity.getAccount().equals(getSystemAccount())) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("非法操作, 删除系统账号");
            }
            // 1、删除管理员表
            adminService.removeById(adminEntity.getAccount());
            // 2、删除用户角色关联表
            LambdaQueryWrapper<UserRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserRoleEntity::getUserId, adminEntity.getAccount());
            userRoleService.remove(lambdaQueryWrapper);
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("管理员 " + adminEntity.getName() + " 删除成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("管理员 " + adminEntity.getName() + " 删除失败");
        }
    }

    @Transactional
    @PostMapping("/muddleheaded")
    public ResponseUtil muddleheaded(@RequestBody AdminEntity adminEntity) {
        String account = StpUtil.getLoginId().toString();

        if (account.equals(adminEntity.getAccount())) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("不能向自己转岗");

        ArrayList<AdminJobRecordEntity> arrayList = new ArrayList<>();

        DateTime date = DateUtil.date();
        // 接岗
        AdminJobRecordEntity adminJobRecord = new AdminJobRecordEntity();
        adminJobRecord.setAccount(adminEntity.getAccount());
        adminJobRecord.setOnGuard(true);
        adminJobRecord.setStartingDate(date);

        arrayList.add(adminJobRecord);

        // 离岗（除系统账号）
        if (!account.equals(getSystemAccount())) {
            AdminJobRecordEntity adminJobRecord1 = new AdminJobRecordEntity();
            adminJobRecord1.setAccount(account);
            adminJobRecord1.setOnGuard(false);
            adminJobRecord1.setLaidOffTime(date);
            arrayList.add(adminJobRecord1);
        }


        try {
            adminJobRecordService.saveOrUpdateBatch(arrayList);
            StpUtil.logout();
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("向 " + adminEntity.getName() + " 转岗成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("转岗失败，请刷新重试");
        }
    }
}
